<template>
  <div class="gzl">
    <div class="search">
      <hy-search
        class="search_box"
        ref="query"
        :searchTitle="searchTitle"
        v-model="searcher"
        :button="{btnShowBy3:true}"
        :buttonText="{btnNameBy3:'新建退货'}"
        :col="6"
        @search="getList(0)"
        @clickbybtn3="addReturnGoods"
      ></hy-search>
    </div>
    <el-table class="table" stripe :data="tableData_RETURN" style="width: 100%" height="580">
      <el-table-column type="index" label="序号" align="center" width="70"/>
      <el-table-column prop="tuihuoDanhao" label="退货单号" align="center"/>
      <el-table-column prop="supplierName" label="供应商名称" align="center"/>
      <el-table-column label="退货时间" align="center">
        <template v-slot="scope">
          <span>{{ renderTime(scope.row.createonTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template v-slot="scope">
          <span v-show="scope.row.status==1">待审核</span>
          <el-button v-if="scope.row.status == 2" type="text" size="medium"
                     @click="getBOhui(scope.row.checkflowId)">驳回
          </el-button>
<!--          <span v-show="scope.row.status==2">驳回</span>-->
          <span v-show="scope.row.status==3">待发货</span>
          <span v-show="scope.row.status==4">已完成</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="showDetail(scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--========================新增退货弹框=================================-->
    <el-dialog :visible.sync="dialogTableVisible_rd" :modal-append-to-body="false" width="1300px">
      <div class="herd_bud"></div>
      <div class="from_bt">新增退货</div>
      <br/>
      <p class="Purchase_Division"></p>
      <br/>
      <el-row :gutter="32">
        <el-col :span="6">
          <el-form :model="formInlineSupplier" class="demo-form-inline" label-width="83px">
            <el-form-item label="供应商">
              <el-select v-model="supplierNameSec" @change="getsupplierProducts">
                <el-option
                  v-for="item in options_supplier"
                  :key="item.Id"
                  :label="item.supplierName"
                  :value="item.supplierName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <!--<el-col :span="6">
          <el-form :model="formInlineSupplier" class="demo-form-inline" label-width="83px">
            <el-form-item label="运输方式">
              <el-select v-model="formInlineSupplier.value">
                <el-option
                  v-for="item in options_transport"
                  :key="item.value"
                  :label="item.msg"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>-->
        <el-col :span="6">
          <el-button type="primary" plain @click="addRow">新增</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="tableData_tuiHuo"
        style="width: 100%;background-color:#fff"
        height="400"
        :max-height="400"
        stripe
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column>-->
        <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
        <el-table-column label="产品图号" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.productNumber" @change="currentChangeProduct($event,scope.$index)">
              <el-option
                v-for="item in options_PRODUCTS"
                :key="item.id"
                :label="item.productNumber"
                :value="item.productNumber"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center">
          <template slot-scope="scope">
            <el-input disabled v-model="scope.row.productName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" width="90">
          <template slot-scope="scope">
            <el-input disabled v-model="scope.row.danwei"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价(元)" align="center" width="90">
          <template slot-scope="scope">
            <el-input disabled v-model="scope.row.price"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop label="成品库数量" align="center" width="100">
          <template slot-scope="scope">
            <el-input @input="checkNumber_chengpin(scope.$index)" v-model="scope.row.chengpinNumber_return">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop label="废品库数量" align="center" width="100">
          <template slot-scope="scope">
            <el-input @input="checkNumber_feipin(scope.$index)" v-model="scope.row.feipinNumber_return"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop label="退货总数量" align="center" width="100">
          <template slot-scope="scope">
            <el-input disabled v-model="scope.row.returnGoodTotal"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop label="小计(元)" align="center" width="100">
          <template slot-scope="scope">
            <el-input disabled v-model="scope.row.totalMoney"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="resetForm(scope)"
              size="small"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <div class="from_tab_btn">
        <el-button @click="Confirm" type="primary" size="small">确认</el-button>
        <el-button @click="dialogTableVisible_rd = false" type="info" size="small">取消</el-button>
      </div>
    </el-dialog>
    <!--==========================详情==============================================-->
    <el-dialog :visible.sync="dialogTableVisible_detail" :modal-append-to-body="false" width="1300px">
      <div class="herd_bud"></div>
      <div class="from_bt">退货详情</div>
      <div style="width: 100%;height: 60px;border-top: 1px solid rgb(220, 222, 226);padding-top: 10px">
        <span style="display: inline-block;font-size: 14px;color: #333333;width: 80px">供货商:</span>
        <el-input disabled style="width: 220px" v-model="detail.supplierName"></el-input>
      </div>
      <div style="width: 100%">
        <span>产品：</span>
        <el-table
          :data="tableData_PRODUCTDETAIL"
          style="width: 100%;height: 300px"
          :max-height="300"
        >
          <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
          <el-table-column prop="productNumber" label="产品图号" width="180" align="center"></el-table-column>
          <el-table-column
            prop="productName"
            label="产品名称"
            align="center">
          </el-table-column>
          <el-table-column
            prop="price"
            label="单价(元)"
            align="center">
          </el-table-column>
          <el-table-column
            prop="danwei"
            label="单位"
            align="center">
          </el-table-column>
          <el-table-column
            prop="chengpinkuNumber"
            label="成品退货数"
            align="center">
          </el-table-column>
          <el-table-column
            prop="feipinkuNumber"
            label="废品退货数"
            align="center">
          </el-table-column>
          <el-table-column
            prop="moneySum"
            label="小计"
            align="center">
          </el-table-column>
          <el-table-column
            prop="number"
            label="退货总数"
            align="center">
          </el-table-column>
        </el-table>
      </div>
      <div class="from_tab_btn">
        <!-- <el-button @click="Confirm" type="primary" size="small">确认</el-button>-->
        <el-button @click="dialogTableVisible_detail = false" type="info" size="small">取消</el-button>
      </div>
    </el-dialog>
    <div class="pgnt">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="Pagination.current"
        :page-size="Pagination.pagesize"
        @current-change="handleCurrentChange"
        :total="Pagination.total"
      ></el-pagination>
    </div>

    <el-dialog
      title="驳回详情"
      :visible.sync="dialogVisible_bohui"
      width="50%"
      :modal-append-to-body="false">
      <ul :data="bohuilist" class="bohuizujian">
        <li>
          <span>审核日期</span>
          <el-input v-model="bohuilist.checkTime" style="width: 70%;" disabled></el-input>
        </li>
        <li>
          <span>审核人</span>
          <el-input v-model="bohuilist.userName" style="width: 70%;" disabled></el-input>
        </li>
        <li>
          <span>驳回理由</span>
          <el-input v-model="bohuilist.bohuiReason" style="width: 70%;" disabled></el-input>
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="dialogVisible_bohui = false">返 回</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  inject: ['reload'],
  name: "ReturnGoodsManage",
  components: {},
  data() {
    return {
      dialogVisible_bohui: false,
      bohuilist:{
        bohuiReason:"",
        checkTime:"",
        userName:"",
      },
      detail: {},
      tableData_PRODUCTDETAIL: [],
      tableData_RETURN: [],
      chengpinNumber_return: 0,
      feipinNumber_return: 0,
      options_PRODUCTS: [],//产品的options
      productNumberSec: "",//选中的的产品图号的
      enterpriseNumberSec: "",//选中的供应商的编号
      supplierNameSec: "",//选中的供应商的名称
      enterpriseSec: {},//选中的供应商的对象
      tableData_tuiHuo: [],//退货
      options_supplier: [],//供应商集合
      allProducts: [],//所有的产品集合
      ownProducts: [],//供应商自己的产品的集合
      options_transport: [//运输方式
        {value: 1, msg: "快递"},
        {value: 2, msg: "物流"},
        {value: 3, msg: "自提"},
      ],
      dialogTableVisible_detail: false,
      dialogTableVisible_rd: false,
      formInlineSupplier: {},
      searchTitle: [
        {
          type: "input",
          name: "customProductName",
          label: "输入搜索",
          placeholder: "请输入退货编号",
          prop: "customProductName"
        },
        {
          type: "date2",
          name: "issuanceDate",
          label: "输入时间",
          placeholder: "请选择输入时间",
          prop: "issuanceDate"
        }
      ],
      searcher: {
        customProductName: "",
        customProductNo: "",
        issuanceDate: ""
      },
      tableData: [],
      Pagination: {
        beginTime: "",
        endTime: "",
        key: "",
        total: 1,//总共页
        current: 1,//当前页
        pagesize: 10,//页面数据个数
      },
    };
  },
//监听属性 类似于data概念",
  computed: {},
//监控data中的数据变化",
  watch: {},
//方法集合",
  methods: {
    getBOhui(checkflowId) {
      this.dialogVisible_bohui = true
      axios("/JX_java/procurement/getCheckFlowDetails?checkFlowId=" + checkflowId).then((res) => {
        console.log(res)
        let relse = res.data.data
        this.bohuilist = relse
        console.log(this.bohuilist)
      })
    },

    showDetail(data) {
      axios.get("/JX_java/procurement/tuihuo/getProductRetrurnDetails?tableId=" + data).then(res => {
        console.log(res.data.data)
        this.detail.supplierName = res.data.data.supplierName
        this.tableData_PRODUCTDETAIL = res.data.data.warehouseLogs;
        this.dialogTableVisible_detail = true;
      })

    },
    //格式化时间
    renderTime(date) {
      return date==null?"":date.substring(0, 10);

      // const dateee = new Date(date).toJSON();
      // if (date == null) {
      //   return "---";
      // } else {
      //   return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
      // }
    },
    //校验成品输入的大小
    checkNumber_chengpin(index) {
      if (this.tableData_tuiHuo[index].chengpinNumber_return > this.tableData_tuiHuo[index].chengpinNumber) {
        this.$message.error("对不起，成品退货不能输入大于" + this.tableData_tuiHuo[index].chengpinNumber)
        this.tableData_tuiHuo[index].chengpinNumber_return = 0;
      }
      if (parseInt(this.tableData_tuiHuo[index].chengpinNumber_return) == NaN) {
        this.tableData_tuiHuo[index].chengpinNumber_return = 0
      }
      if (parseInt(this.tableData_tuiHuo[index].feipinNumber_return) == NaN) {
        this.tableData_tuiHuo[index].feipinNumber_return = 0
      }
      console.log(parseInt(this.tableData_tuiHuo[index].chengpinNumber_return), parseInt(this.tableData_tuiHuo[index].feipinNumber_return));
      this.tableData_tuiHuo[index].returnGoodTotal = parseInt(this.tableData_tuiHuo[index].chengpinNumber_return) + parseInt(this.tableData_tuiHuo[index].feipinNumber_return);
      this.tableData_tuiHuo[index].totalMoney = this.tableData_tuiHuo[index].returnGoodTotal * this.tableData_tuiHuo[index].price
    },
    //校验废品库输入的大小
    checkNumber_feipin(index) {
      if (this.tableData_tuiHuo[index].feipinNumber_return > this.tableData_tuiHuo[index].feipinNumber) {
        this.$message.error("对不起，废品退货不能输入大于" + this.tableData_tuiHuo[index].feipinNumber)
        this.tableData_tuiHuo[index].feipinNumber_return = 0;
      }
      this.tableData_tuiHuo[index].returnGoodTotal = parseInt(this.tableData_tuiHuo[index].chengpinNumber_return) + parseInt(this.tableData_tuiHuo[index].feipinNumber_return);
      this.tableData_tuiHuo[index].totalMoney = this.tableData_tuiHuo[index].returnGoodTotal * this.tableData_tuiHuo[index].price
    },
    Confirm: function () {
      if (Object.keys(this.enterpriseSec).length == 0) {
        this.$message.error("供应商不能为空")
        return;
      }
      let message = JSON.parse(localStorage.getItem("message"));
      const data = {
        "carName": "",
        "carNumber": "",
        "carPhone": "",
        "createonTime": "",
        "fahuoTime": "",
        "id": 0,
        "kuaidiDanhao": "",
        "only": 0,
        "status": 0,
        "supplierId": this.enterpriseSec.supplierId,
        "supplierName": this.enterpriseSec.supplierName,
        "tuohuoDanhao": "",
        "type": this.formInlineSupplier.value,
        "userId": message.Id,
        "userName": message.Name,
        "warehouseLogs": []
      }
      console.log(this.tableData_tuiHuo)
      this.tableData_tuiHuo.forEach(e => {
        const warehouseLog = {
          "chengpinkuNumber": parseInt(e.chengpinNumber_return),
          "createonTime": "",
          "createonUserid": message.Id,
          "createonUsername": this.enterpriseSec.supplierName,
          "feipinkuNumber": parseInt(e.feipinNumber_return),
          "id": 0,
          "isJiesuan": 0,
          "number": parseInt(e.chengpinNumber_return) + parseInt(e.feipinNumber_return),
          "orderProductId": 0,
          "productName": e.productName,
          "productNumber": e.productNumber,
          "rukuTime": "",
          "rukuUserid": 0,
          "rukuUsername": "",
          "saleslogId": 0,
          "sorpId": 0,
          "status": 0,
          "supplierId": this.enterpriseSec.supplierId,
          "tableId": 0,
          "type": 0,
          "warehouseId": e.id,
          "danwei": e.danwei,
          "price": e.price,
          "moneySum": e.totalMoney,
        }
        data.warehouseLogs.push(warehouseLog)
      })
      console.log(data, "后台数据")
      axios.post("/JX_java/procurement/tuihuo/addTuihuo", data).then(res => {
        console.log(res.data)
        if (res.data.data == "操作成功") {
          this.$message.success(res.data.data);
          this.reload();
          this.dialogTableVisible_rd = false
        } else {
          this.$message.success(res.data.data);
        }
      })
    },
    currentChangeProduct(event, index) {
      console.log(event, index)
      this.options_PRODUCTS.forEach(e => {
        if (e.productNumber == event) {
          this.tableData_tuiHuo[index].id=e.id
          this.tableData_tuiHuo[index].productName = e.productName
          this.tableData_tuiHuo[index].danwei = e.danwei
          this.tableData_tuiHuo[index].productNumber = e.productNumber
          this.tableData_tuiHuo[index].chengpinNumber = e.chengpinNumber
          this.tableData_tuiHuo[index].feipinNumber = e.feipinNumber
          this.tableData_tuiHuo[index].price = e.price
        }
      })

    },
    //依据供应商的id 获取旗下的所有的产品
    getsupplierProducts(data) {
      this.tableData_tuiHuo = []
      this.productNumberSec = ""
      this.options_supplier.forEach(e => {
        if (e.supplierName == data) {
          this.enterpriseSec = e;
          console.log(this.enterpriseSec, "选中的对象")//ownProducts
          this.options_PRODUCTS = this.enterpriseSec.warehouses

        }
      })
    },
    getAllProducts() {
      let message = JSON.parse(localStorage.getItem("message"));
      axios.get("/JX_java/common/getproductSupplier?udserId=" + message.Id).then(res => {
        console.log(res.data.data, "所有的供应商的产品集合")
        this.allProducts = res.data.data
        //this.options_supplier
        this.options_supplier = this.allProducts
      })
    },
    //动态添加行
    addRow() {
      const list = {
        tuHao: "",
        chengpinNumber_return: 0,
        feipinNumber_return: 0,
        totalMoney: 0,
      };
      this.tableData_tuiHuo.push(list);
    },
    //动态删除行
    resetForm(e) {
      this.tableData_tuiHuo.splice(e.$index, 1);
    },
    //列表
    getList() {
      const data = {
        "beginTime": "",
        "endTime": "",
        "key": "",
        "pageNum": 0,
        "pageSize": 0,
        "type": 0
      }
      let parse = JSON.parse(localStorage.getItem("message"));
      axios.post("/JX_java/procurement/tuihuo/getProductReturnList?userId=" + parse.Id + "&&type=" + 1, data).then(res => {
        console.log(res.data.data, "列表展示")
        this.tableData_RETURN = res.data.data.content
      })
    },
    addReturnGoods() {
      this.dialogTableVisible_rd = true;
    },
    // 分页
    handleCurrentChange(e) {
      this.getData(e - 1)
    },
    // 日期改变
    chage(e) {
      if (e) {
        this.start =
          e[0].getFullYear() +
          '-' +
          (e[0].getMonth() + 1) +
          '-' +
          e[0].getDate()
        this.end =
          e[1].getFullYear() +
          '-' +
          (e[1].getMonth() + 1) +
          '-' +
          e[1].getDate()
      } else {
        this.start = ''
        this.end = ''
      }
    },
    // 筛选
    onsubmit() {
      this.getData()
    }
  },
//生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate() {
  },
//生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created() {
    this.getList();
    this.getAllProducts();
  },
//生命周期 - 挂载之前",html模板未渲染
  beforeMount() {
  },
//生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted() {
  },
//生命周期 - 更新之前",数据模型已更新,html模板未更新
  beforeUpdate() {
  },
//生命周期 - 更新之后",数据模型已更新,html模板已更新
  updated() {
  },
//生命周期 - 销毁之前",
  beforeDestroy() {
  },
//生命周期 - 销毁完成",
  destroyed() {
  },
//如果页面有keep-alive缓存功能，这个函数会触发",
  activated() {
  },
}
</script>

<style lang="scss" scoped>
.bohuizujian{
  display: flex;
  flex-wrap: wrap;
  li{
    width: 33%;
    padding-top: 10px;
    text-align: center;
    span{
      display: inline-block;
      width: 25%;
    }
  }
}

.from_bt {
  color: #17233D;
  font-style: normal;
  font-size: 18px;
  font-weight: 700;
}

.gzl {
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
}

.table {
  margin-bottom: 20px;
}

.pgnt {
  text-align: center;
}

.demo-form-inline {
  display: inline-block;
}

.search {
  height: 50px;
  border-radius: 5px;
  background-color: #fff;
  padding-left: 20px;
  padding-top: 10px;
  margin-bottom: 20px;
  overflow: hidden;
}

.ebtn {
  float: right;
  margin-right: 20px;
}

.from_tab_btn {
  margin-top: 10px;
  text-align: center;
}
</style>
